<template>
  <div class="add-container">
    <el-form
      ref="editForm"
      :rules="roleRules"
      :model="editForm"
      label-width="100px"
      label-position="left"
    >
      <h4>基本信息</h4>
      <el-divider />
      <el-form-item label="角色名称: " prop="name">
        <el-input v-model="editForm.name" />
      </el-form-item>
      <el-form-item label="角色描述: " prop="description">
        <el-input v-model="editForm.description" />
      </el-form-item>
      <el-form-item label="状态选择: " prop="status">
        <el-radio v-model="editForm.status" :label="1">启用</el-radio>
        <el-radio v-model="editForm.status" :label="2">禁用</el-radio>
      </el-form-item>
      <el-form-item label="赋予权限:" prop="checks">
        <el-tree
          ref="tree"
          class="tree-checks role-input"
          :data="routesData"
          show-checkbox
          default-expand-all
          node-key="id"
          :default-checked-keys="editForm.checks"
          highlight-current
          :props="defaultProps"
          @check-change="nodeChange"
        />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submit">
        确定
      </el-button>
    </div>
  </div>
</template>

<script>
import { deepClone } from '@/utils'
import { getRoleShow, addRole, updateRole } from '@/api/role'
import { getPermissionList } from '@/api/auth'
import checkPermission from '@/utils/permission' // 权限判断函数
import { closeSelectedTagToCustom } from '@/utils/index'

const defaultRole = {
  id: undefined,
  name: '',
  description: '',
  status: '',
  node: [],
  checks: []
}

export default {
  name: 'RolePermissionAdd',
  data() {
    const validateNode = (rule, value, callback) => {
      const arr = this.$refs.tree.getCheckedKeys()
      if (arr.length === 0 || !arr) {
        callback(new Error('请赋予权限'))
      } else {
        callback()
      }
    }
    return {
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      permissions: [],
      editForm: Object.assign({}, defaultRole),
      roleRules: {
        name: [
          { required: true, trigger: 'blur', message: '请输入角色名' }
        ],
        description: [
          { required: true, trigger: 'blur', message: '请输入描述' }
        ],
        status: [
          { required: true, trigger: 'blur', message: '请选择状态' }
        ],
        node: [
          { required: true, trigger: 'blur', validator: validateNode }
        ],
        checks: [
          { required: true, trigger: 'blur', message: '请选择权限' }
        ]
      }
    }
  },
  computed: {
    routesData() {
      return this.permissions
    }
  },
  mounted() {
    if (this.$route.query.id) {
      this.edit()
    } else {
      this.add()
    }
  },
  created() {
    this.allPermissions()
  },
  methods: {
    checkPermission,
    headerStyle({ row, rowIndex }) {
      return 'table-th'
    },
    add() {
      this.editForm = Object.assign({}, defaultRole)
      if (this.$refs.tree) {
        this.$refs.tree.setCheckedKeys([])
      }
      this.title = '新增角色'
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.editForm.clearValidate()
      })
    },
    edit() {
      getRoleShow(this.$route.query.id).then((response) => {
        const { item } = response.data
        this.editForm = deepClone(item)
        if (this.$refs.tree) {
          this.$refs.tree.setCheckedKeys(item.checks)
        }
        this.$nextTick(() => {
          this.$refs.editForm.clearValidate()
        })
      })
    },
    nodeChange() {
      this.editForm.checks = this.$refs.tree.getCheckedKeys()
      this.editForm.node = this.$refs.tree.getHalfCheckedKeys().concat(this.editForm.checks)
    },
    submit() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          if (this.editForm.id !== undefined) {
            updateRole(this.editForm).then(() => {
              this.$message.success('修改成功')
              closeSelectedTagToCustom(this.$route.path, '/admin/role')
            })
          } else {
            addRole(this.editForm).then(() => {
              this.$message.success('添加成功')
              closeSelectedTagToCustom(this.$route.path, '/admin/role')
            })
          }
        } else {
          return false
        }
      })
    },
    // 获取权限节点
    allPermissions() {
      getPermissionList().then((response) => {
        const { data } = response
        this.permissions = data.list
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.tree-checks{
  height:550px;
  overflow-y:auto;
}

.role-input{
  width:320px
}
</style>
